package com.sky.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2024/1/24 10:53
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {
    private final AddressBookMapper addressBookMapper;
    private final OrderMapper orderMapper;
    private final OrderDetailMapper orderDetailMapper;
    private final ShoppingCartMapper shoppingCartMapper;
    private final UserMapper userMapper;
    private final WeChatPayUtil weChatPayUtil;

    /**
     * 提交订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //0、数据校验（地址校验、购物车校验）
        // 地址校验
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (ObjectUtil.isEmpty(addressBook)) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 购物车校验(是否为空)
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.queryByParams(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());
        if (ObjectUtil.isEmpty(shoppingCarts)) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1、将订单数据保存到订单表
        Orders orders = Orders.builder().build();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setUserName(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        this.orderMapper.save(orders);

        //2、将订单商品信息保存到订单明细表
        List<OrderDetail> orderDetails = new ArrayList<>(shoppingCarts.size());
        shoppingCarts.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });

        this.orderDetailMapper.batchSave(orderDetails);

        //3、清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());

        //4、构建VO数据，返回
        return OrderSubmitVO.builder().id(orders.getId()).orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount()).orderNumber(orders.getNumber()).build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 历史订单查询
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQueryOrder(Integer page, Integer pageSize, Integer status) {
        //1、使用PageHelper设置分页参数（page、pagesize、order）
        PageHelper.startPage(page, pageSize);
        //2、分页查询
        Page<List<OrderVO>> p = orderMapper.pageQueryOrder(status);
        //3、封装结果集
        return new PageResult(p.getTotal(), p.getResult());
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO queryById(Integer id) {
        return orderMapper.queryById(id);
    }


    /**
     * 派送订单
     *
     * @param id
     * @return
     */
    @Override
    public void delivery(Long id) {
        orderMapper.updateId(id);
    }

    /**
     * 完成订单
     *
     * @param id
     * @return
     */
    @Override
    public void deliverySuccess(Long id) {
        orderMapper.updateIds(id);
    }

    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Override
    public void cancelOrder(Integer id) {
        orderMapper.cancelOrder(id);
    }

    /**
     * 再来一单
     *
     * @param id
     * @return
     */
    @Override
    public void repetitionOrder(Integer id) {
        List<OrderDetail> orderDetail = orderMapper.queryOrdersById(id);
        List<ShoppingCart> list = new ArrayList<>(orderDetail.size());

        for (OrderDetail detail : orderDetail) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(detail, shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setId(null);
            list.add(shoppingCart);
        }
        shoppingCartMapper.saveList(list);
    }

    /**
     * 管理端查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        OrderVO orderVO = orderMapper.getVoById(id);
        return orderVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersConfirmDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以接单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        orderMapper.update(orders);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);

        if (ObjectUtils.isNotEmpty(page.getResult())) {
            page.getResult().forEach(orderVO -> {
                // 将每一条订单菜品信息拼接为字符串
                String orderDishes = orderVO.getOrderDetailList().stream().map(x -> {
                    String orderDish = x.getName() + "," + x.getNumber() + ";";
                    return orderDish;
                }).collect(Collectors.joining(""));

                orderVO.setOrderDishes(orderDishes);
            });
        }
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public OrderStatisticsVO statistics() {
        List<Map> result = orderMapper.countStatusByGroup();
        Map<Integer, Integer> resultMap = result.stream().collect(Collectors.toMap(r -> (Integer) r.get("status"), r -> Integer.valueOf(r.get("num").toString())));

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(resultMap.getOrDefault(Orders.TO_BE_CONFIRMED, 0));
        orderStatisticsVO.setConfirmed(resultMap.getOrDefault(Orders.CONFIRMED, 0));
        orderStatisticsVO.setDeliveryInProgress(resultMap.getOrDefault(Orders.DELIVERY_IN_PROGRESS, 0));
        return orderStatisticsVO;
    }


    /**
     * 拒绝接单
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersRejectionDTO, orders);
        // 判断订单状态是否为待处理
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            orders = Orders.builder()
                    .id(orders.getId())
                    .status(Orders.CANCELLED)
                    .payStatus(Orders.REFUND)
                    .rejectionReason(orders.getRejectionReason())
                    .build();
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException("订单状态不正确");
        }
    }


    /**
     * 取消订单
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        // 判断订单状态是否为待处理
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            orders = Orders.builder()
                    .id(orders.getId())
                    .status(Orders.CANCELLED)
                    .payStatus(Orders.REFUND)
                    .cancelReason(orders.getCancelReason())
                    .cancelTime(LocalDateTime.now())
                    .build();
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException("订单状态不正确");
        }
    }

}
